package com.media.appmedia.fragment;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.json.JSONArray;
import org.json.JSONException;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.media.appmedia.R;
import com.media.appmedia.activity.AdWebView;
import com.media.appmedia.activity.EnvelopeActivity;
import com.media.appmedia.activity.EventChannelActivity;
import com.media.appmedia.activity.PromotionRichActivity;
import com.media.appmedia.activity.ShareActivity2;
import com.media.appmedia.activity.ShopActivity;
import com.media.appmedia.base.BaseApplication;
import com.media.appmedia.clicks.ViewPagerAdOncliecks;
import com.media.appmedia.clicks.ViewPagerAdOncliecks.ResultUrl;
import com.media.appmedia.entity.ImageAdBean;
import com.media.appmedia.entity.UserGradeInfo;
import com.media.appmedia.network.ProtocolService;
import com.media.appmedia.slidingmenu.IntegralActivity;
import com.media.appmedia.util.MethodUtils;
import com.media.appmedia.util.PhoneInfoUtils;
import com.media.appmedia.util.ToastUtils;
import com.media.appmedia.view.AutoScrollViewPager;
import com.slidingmenu.lib.SlidingMenu;

/**
 * 
 * <pre>
 * 业务名:
 * 功能说明: 首页功能
 * 编写日期:	2014-10-31
 * 作者:	 Rose
 * 
 * 历史记录
 * 1、修改日期：
 *    修改人：Rose
 *    修改内容：移植MainActivity中的逻辑
 * </pre>
 */
public class MyFragement extends Fragment implements OnClickListener {

	private Context mContext;
	private ArrayList<ImageAdBean> listImageBean;
	private ImageView[] imageViews = null;
	private ImageView imageView = null;
	// private ViewPager advPager = null;
	private AtomicInteger what = new AtomicInteger(0);
	private boolean isContinue = true;
	private View mView;
	private SlidingMenu slidingMenu;
	private ImageButton mImageqian, mImageMingxi, mImage2, mImage3, mImage4,
			mImage5;
	private TextView mTvQiandao , mTvMinxi;
	private ImageButton menvelope;
	private ImageButton mSlidingMenu;
	@ViewInject(R.id.adv_pager)
	private AutoScrollViewPager viewPager;
	@ViewInject(R.id.imagedeng)
	private TextView mGrade;
	@ViewInject(R.id.imageqiandao)
	private ImageButton imageButtonQ;
	@ViewInject(R.id.envelope)
	private ImageButton messge;
	@ViewInject(R.id.imagejin)
	private TextView mGold;
	private ViewPagerAdOncliecks adOncliecks;
	private int imageR[] = new int [] {
			R.drawable.viewpage1 ,
			R.drawable.viewpage2 ,
			R.drawable.viewpage3 ,
	};
	private List<View> advPics;
	private AdvAdapter adapter;

	private int xinfen;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		mView = inflater.inflate(R.layout.myfragment, null);
		slidingMenu = BaseApplication.getApplication().getmSlidingMenu();
		mContext = getActivity();
		ViewUtils.inject(this, mView);
		// 检测是否有新信息
		isMessge();

		initView(mView);
		initViewPager(mView, null);
//		setViewPager(mView);
		return mView;
	}

	private void isMessge() {
		ProtocolService.getMessge(PhoneInfoUtils.getIMEI(getActivity()),
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						try {
							org.json.JSONObject obj = new org.json.JSONObject(
									arg0.result);
							int x = obj.getInt("message");
							int y = MethodUtils.getMessge(getActivity());
							xinfen = y;
							if (y < x) {
								messge.setImageResource(R.drawable.xinfeng_s);
								xinfen = x;
							} else {
								messge.setImageResource(R.drawable.xinfeng);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}

					}

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						System.out.println("");
					}
				});
	}

	@Override
	public void onStart() {
		super.onStart();
		if (BaseApplication.getApplication().getIsSign() != 1) {
//			imageButtonQ.setBackgroundResource(R.drawable.yiqian);
		}
		setGrad(PhoneInfoUtils.getIMEI(mContext));
	}

	/**
	 * 
	 * 方法说明：用于设置首页等级和金币的获取和展示
	 * 
	 */
	private void setGrad(String biaozhifu) {
		ProtocolService.getVerifyMy(biaozhifu, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				System.out.println();
				UserGradeInfo info = JSONObject.parseObject(arg0.result,
						UserGradeInfo.class);
				if (info.getMessage() == 1) {
					mGrade.setText("" + info.getRegular_name());
					mGold.setText("" + (int) info.getIntegral_grande());
				}
			}

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				ToastUtils.show(getActivity().getApplicationContext(),
						R.string.phone_verify_send_fail);
			}
		});
	}

	private void initView(View view) {
		// 主图片按钮
		mImageqian = (ImageButton) view.findViewById(R.id.imageqiandao);
		mImageMingxi = (ImageButton) view.findViewById(R.id.imagemingmxi);
		mTvQiandao = (TextView) view.findViewById(R.id.imageqiandao2);
		mTvMinxi = (TextView) view.findViewById(R.id.imagemingmxi2);
		mImage2 = (ImageButton) view.findViewById(R.id.ImageMain3);
		mImage3 = (ImageButton) view.findViewById(R.id.ImageMain4);
		mImage4 = (ImageButton) view.findViewById(R.id.ImageMain5);
		mImage5 = (ImageButton) view.findViewById(R.id.ImageMain6);
		// 信封
		menvelope = (ImageButton) view.findViewById(R.id.envelope);
		// 侧滑菜单
		mSlidingMenu = (ImageButton) view.findViewById(R.id.slidingmenu);
		mSlidingMenu.setOnClickListener(this);
		mImageqian.setOnClickListener(this);
		mImageMingxi.setOnClickListener(this);
		mTvQiandao.setOnClickListener(this);
		mTvMinxi.setOnClickListener(this);
		mImage2.setOnClickListener(this);
		mImage3.setOnClickListener(this);
		mImage4.setOnClickListener(this);
		mImage5.setOnClickListener(this);
		menvelope.setOnClickListener(this);

		advPics = new ArrayList<View>();
		viewPager.setOffscreenPageLimit(5);
		adapter = new AdvAdapter(advPics);
		viewPager.setAdapter(adapter);
		viewPager.setCycle(true);
		viewPager.setInterval(4000);
		viewPager.setAutoScrollDurationFactor(10);
		viewPager.startAutoScroll();

	}

	/**
	 * 
	 * 方法说明：网络下载图片进行适配
	 * 
	 * @param mView
	 */
	private void setViewPager(final View mView) {
		ProtocolService.setViewPager(PhoneInfoUtils.getIMEI(getActivity()),
				new RequestCallBack<String>() {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						try {
							org.json.JSONObject obj1 = new org.json.JSONObject(
									responseInfo.result);
							if (obj1.getInt("message") == 1) {
								JSONArray array = obj1.getJSONArray("0");
								listImageBean = new ArrayList<ImageAdBean>();
								for (int i = 0; i < array.length(); i++) {
									org.json.JSONObject obj2 = (org.json.JSONObject) array
											.get(i);
									ImageAdBean adBean = new ImageAdBean();
									adBean.setRoll_image_url(obj2
											.getString("roll_image_url"));
									adBean.setRoll_image_photo(obj2
											.getString("roll_image_photo"));
									listImageBean.add(adBean);
								}
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}

						adOncliecks = new ViewPagerAdOncliecks(listImageBean,
								new ResultUrl() {

									@Override
									public void setUrl(String url) {
										if (!MethodUtils.isEmpty(url)) {
											Intent intent = new Intent(
													getActivity(),
													AdWebView.class);
											intent.putExtra("url", url);
											startActivity(intent);
										}
									}
								});
						initViewPager(mView, listImageBean);
					}

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						ToastUtils.show(getActivity().getApplicationContext(),
								R.string.phone_verify_send_fail);
					}
				});
	}

	/**
	 * 
	 * 设置广告栏的图片及切换效果
	 */

	private void initViewPager(View view, ArrayList<ImageAdBean> listBean) {
		/**
		 * 解决ViewPager广告展示与SlidingMenu左滑菜单的滑动冲突
		 */
		// BaseApplication.getApplication().getmSlidingMenu()
		// .addIgnoredView(viewPager);
		// 图片列表
		if(listBean == null ){
			for(int i = 0; i <3; i++){
				ImageView views = new ImageView(mContext);
				views.setImageResource(imageR[i]);
				views.setScaleType(ScaleType.FIT_XY);
				advPics.add(views);
			}
		}
		/**
		 * 网络获取轮播图效果  已注释
		 */
//		for (int i = 0; i < listBean.size(); i++) {
//			BitmapUtils utils = new BitmapUtils(mContext);
//			// NetworkImageView views = new NetworkImageView(mContext);
//			ImageView views = new ImageView(mContext);
//			utils.display(views, listBean.get(i).getRoll_image_photo());
//			views.setScaleType(ScaleType.FIT_XY);
//			advPics.add(views);
//		}
		adapter.notifyDataSetChanged();
		ViewGroup group = (ViewGroup) view.findViewById(R.id.viewGroup);
		imageViews = new ImageView[advPics.size()];

		for (int i = 0; i < advPics.size(); i++) {
			imageView = new ImageView(mContext);
			imageView.setLayoutParams(new LayoutParams(20, 20));
			imageView.setPadding(0, 0, 0, 0);
			imageViews[i] = imageView;
			if (i == 0) {
				// 默认选中第一张图片
				imageViews[i]
						.setBackgroundResource(R.drawable.banner_dian_focus);
			} else {
				imageViews[i]
						.setBackgroundResource(R.drawable.banner_dian_blur);
			}
			group.addView(imageViews[i]);
		}

		/**
		 * 启动自动轮播设置
		 */

		/**
		 * ViewPager的滑动监听
		 */
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageSelected(int index) {
				changImageTage(imageViews, index);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});

	}

	/**
	 * 操作圆点轮换变背景
	 */
	private void changImageTage(ImageView[] list, int index) {
		for (int i = 0; i < list.length; i++) {
			list[i].setBackgroundResource(R.drawable.banner_dian_blur);
		}
		list[index].setBackgroundResource(R.drawable.banner_dian_focus);
	}

	/**
	 * 广告栏PaperView 图片适配器
	 * 
	 * @author wx
	 * 
	 */
	private final class AdvAdapter extends PagerAdapter {
		private List<View> views = null;

		public AdvAdapter(List<View> views) {
			this.views = views;
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView(views.get(arg1));
		}

		@Override
		public void finishUpdate(View arg0) {

		}

		@Override
		public int getCount() {
			return views.size();
		}

		@Override
		public Object instantiateItem(View arg0, final int arg1) {
			View ImgView = views.get(arg1);
//			ImgView.setTag(listImageBean.get(arg1).getRoll_image_url());
//			ImgView.setOnClickListener(adOncliecks);
			((ViewPager) arg0).addView(views.get(arg1), 0);
			return views.get(arg1);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {

		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {

		}

	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.imageqiandao:
		case R.id.imageqiandao2:
			if (BaseApplication.getApplication().getIsSign() == 1) {
				Intent intentPromotionRich = new Intent(mContext,
						PromotionRichActivity.class);
				startActivity(intentPromotionRich);
			} else {
				// 当用户不能签到时弹出Dialog提示
				AlertDialog.Builder alertbBuilder = new AlertDialog.Builder(
						getActivity());
				alertbBuilder
						.setTitle("提示")
						.setMessage("您今天已经签到了，明日再签吧")
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// 不做处理
										dialog.cancel();
									}
								})
						.setNegativeButton("取消",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.cancel();

									}
								}).create();
				alertbBuilder.show();
			}
			break;
		case R.id.imagemingmxi:
		case R.id.imagemingmxi2:
			Intent intentdetail = new Intent(mContext, IntegralActivity.class);
			startActivity(intentdetail);
			break;

		case R.id.ImageMain3:
			Intent intentShop = new Intent(mContext, ShopActivity.class);
			startActivity(intentShop);
			break;
		case R.id.ImageMain4:
			BaseApplication.getApplication().getFragmentTabAdapter()
					.setRagItem(R.id.RadioButton2);
			// 调到赚钱
			// Intent intentIntegral = new
			// Intent(mContext,IntegralWallActivity.class);
			// startActivity(intentIntegral);
			break;
		case R.id.ImageMain5:
			Intent intentChannel = new Intent(mContext,
					EventChannelActivity.class);
			startActivity(intentChannel);
			break;
		case R.id.ImageMain6:
			Intent intentGeneralize = new Intent(mContext, ShareActivity2.class);
			startActivity(intentGeneralize);
			break;
		case R.id.slidingmenu:
			if (slidingMenu.isMenuShowing()) {
				slidingMenu.showContent();
			} else {
				slidingMenu.showMenu();
			}
			break;
		case R.id.envelope:
			messge.setImageResource(R.drawable.xinfeng);
			MethodUtils.setMessge(getActivity(), xinfen);
			Intent intentenvelope = new Intent(mContext, EnvelopeActivity.class);
			startActivity(intentenvelope);
			break;
		}
	}

}
